import { getFlowOrgTreeByOrgIDService, getUserDataList } from '@/services/BaseLayout';
import { commonDeptGetUser, getDeptPosTreeIcon, searchChangeColor } from '@/utils';
import { Col, Form, Input, message, Select, TreeSelect } from 'antd';
import { useEffect, useMemo } from 'react';
import MyIcon from '../MyIcon';
import pageStyles from '@/common/pageLayout.less';

const DeptPosLinkageUser: React.FC<DeptPosLinkageUserAPI.IDeptPosLinkageUser> = ({
  colSpan, //所占栅格    必传
  formRef, //表单 form
  isNO_label, //是否展示label  必传

  org_label, //树 下拉label  必传
  user_label, // 下拉菜单名称 | 必传

  notUser = true, //是否展示选择人员  必传

  isDeptRequired = false, //组织机构是否为必填，创建和编辑页面选传，默认false
  isUserRequired = false, // 人员是否为必填，创建和编辑页面选传，默认false

  isNo_selectCompany = true, //是否可选公司  默认为 true   true为可选
  isNO_selectDepartment = true, //是否可选部门  默认 true   true为可选
  isNo_selectPosition = true, // 是否 可选 岗位 默认 为 true   true为可选

  isNO_showPosition = true, // 是否显示岗位数据 默认为 True
  isNo_showDepartment = true, //是否展示部门数据  默认为 true

  isNO_search = false, //是否搜索表单使用 默认 false

  isNo_orgSelectChecks = false, // 组织树下拉框 是否可以多选  默认 false
  isNo_userSelectChecks = false, //人员选择框 是否可以多选  默认 false

  formCompanyID, // form 下拉树结构 公司 | 必传
  formDepartmentID, // form 下拉树结构 部门 | 必传
  formPositionID, // form 下拉树结构 岗位 | 必传
  formUserID, // form 下拉树结构 人 | 必传

  orgamParams, // 获取组织机构参数  必传
}) => {
  /**引入获取组织数据 */
  const { getFlowOrgTreeRun, getFlowOrgList, getFlowOrgTreeLoading } = getFlowOrgTreeByOrgIDService();

  const { getUserRun, getUserLoading, getUserList, pramsObjInfo } = getUserDataList((res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    }
  });

  useEffect(() => {
    if (orgamParams && JSON.stringify(orgamParams) != '{}') {
      getFlowOrgTreeRun(orgamParams);
    }
  }, [orgamParams?.params, orgamParams?.flowType]);

  /**
   * 组织机构是否可选择
   * @param orgObj 树节点
   */
  const isNoSelectOrg = (orgObj: Record<string, any>) => {
    let isSelect: boolean = false;
    if (orgObj?.open) {
      if (orgObj?.textType == '0') {
        isSelect = isNo_selectCompany;
      }
      if (orgObj?.textType == '1') {
        isSelect = isNO_selectDepartment;
      }
      if (orgObj?.textType == '2') {
        isSelect = isNo_selectPosition;
      }
    }
    return !isSelect;
  };

  /**
   * 处理组织结构树数据
   */
  const orgTreeDataMemo = useMemo(() => {
    let loopDept = (dataList: any[]): any[] => {
      return dataList
        ?.map((item: any) => {
          if (item?.textType == '1') {
            if (isNo_showDepartment) {
              const titleTree = searchChangeColor(item?.text, '实验室');
              return {
                ...item,
                title: (
                  <div className={pageStyles['over-flow-hidden']} title={item?.text}>
                    {getDeptPosTreeIcon(String(item?.textType))}
                    {item?.text}
                  </div>
                ),
                searchtitle: item?.text,
                key: item?.id,
                value: item?.id,
                children: item?.children && item?.children?.length > 0 ? loopDept(item?.children) : null,
                disabled: isNoSelectOrg(item),
              };
            }
          } else if (item?.textType == '2') {
            if (isNO_showPosition) {
              return {
                ...item,
                title: (
                  <div className={pageStyles['over-flow-hidden']} title={item?.text}>
                    {getDeptPosTreeIcon(String(item?.textType))}
                    {item?.text}
                  </div>
                ),
                searchtitle: item?.text,
                key: item?.id,
                value: item?.id,
                disabled: isNoSelectOrg(item),
              };
            }
          } else {
            return {
              ...item,
              title: (
                <div className={pageStyles['over-flow-hidden']} title={item?.text}>
                  {getDeptPosTreeIcon(String(item?.textType))}
                  {item?.text}
                </div>
              ),
              searchtitle: item?.text,
              key: item?.id,
              value: item?.id,
              children: item?.children && item?.children?.length > 0 ? loopDept(item?.children) : null,
              disabled: isNoSelectOrg(item),
            };
          }
        })
        ?.filter((itemChild: any) => {
          return itemChild;
        });
    };
    let orgListTree = loopDept(getFlowOrgList);
    return orgListTree;
  }, [getFlowOrgList]);

  /**
   * 点击选中岗位
   * @param selectedKeys
   * @param selectedNodes
   */
  const onTreeSelect = (selectedKeys: any, selectedNodes: any) => {
    let userListPayload = commonDeptGetUser([selectedNodes]);
    checkDeptPOSData(selectedNodes);
    getUserRun({ ...userListPayload });
    formRef?.setFieldValue(formUserID, undefined);
  };

  /**
   * 处理 选中的组织和机构数据
   */
  const checkDeptPOSData = (checkNodes: Record<string, any>) => {
    if (isNO_search) {
      if (checkNodes?.textType == '1') {
        //部门
        formRef?.setFieldsValue({
          [formCompanyID]: checkNodes?.attributes?.companyID || null,
          [formDepartmentID]: checkNodes?.id,
          [formPositionID]: null,
          [formUserID]: null,
        });
      } else if (checkNodes?.textType == '2') {
        //岗位
        formRef?.setFieldsValue({
          [formCompanyID]: checkNodes?.attributes?.companyID || null,
          [formDepartmentID]: checkNodes?.attributes?.departmentID || null,
          [formPositionID]: checkNodes?.id,
          [formUserID]: null,
        });
      }
    } else {
      // if()
      formRef?.setFieldsValue({});
    }
  };

  return (
    <>
      <Col md={colSpan ? colSpan : 8} sm={24}>
        <Form.Item
          label={isNO_label ? org_label : ''}
          name={'CompanDeptPos'}
          rules={[
            {
              required: isDeptRequired,
              message: `请选择${org_label}`,
            },
          ]}
        >
          <TreeSelect
            allowClear={true}
            placeholder={isNO_search ? org_label : `请选择${org_label}`}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeNodeFilterProp="searchtitle"
            treeDefaultExpandAll={false}
            showSearch={true}
            loading={getFlowOrgTreeLoading || getUserLoading}
            treeData={orgTreeDataMemo}
            treeCheckStrictly={isNo_orgSelectChecks}
            treeCheckable={isNo_orgSelectChecks}
            maxTagCount={1}
            onSelect={onTreeSelect}
            popupClassName={pageStyles['treeSelectPopupClassName']}
          />
        </Form.Item>
      </Col>
      {notUser ? (
        <>
          <Col md={colSpan ? colSpan : 8} sm={24}>
            <Form.Item
              label={isNO_label ? user_label : ''}
              name={formUserID}
              rules={[
                {
                  required: isUserRequired,
                  message: `请选择${user_label}`,
                },
              ]}
            >
              <Select
                placeholder={isNO_search ? user_label : `请选择${user_label}`}
                allowClear={true}
                showSearch
                mode={isNo_userSelectChecks ? 'multiple' : undefined}
                maxTagCount={1}
                loading={getFlowOrgTreeLoading || getUserLoading}
              >
                {getUserList?.map((item: any) => {
                  return (
                    <Select.Option
                      // disabled={item?.id == getUserID() ? true : false}
                      value={item?.id}
                      key={item?.id}
                      searchtitle={item?.realName}
                    >
                      <MyIcon style={{ marginRight: 5 }} type="icon-lianxiren" />
                      {item?.realName}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>
        </>
      ) : (
        <></>
      )}

      <Form.Item style={{ display: 'none' }} name={formCompanyID}>
        <Input hidden />
      </Form.Item>
      <Form.Item style={{ display: 'none' }} name={formDepartmentID}>
        <Input hidden />
      </Form.Item>
      <Form.Item style={{ display: 'none' }} name={formPositionID}>
        <Input hidden />
      </Form.Item>
    </>
  );
};

export default DeptPosLinkageUser;
